package com.mypage.view.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MessageNumX;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.impl.ApprovalEngineImpl;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.view.activity.TaskManagementActivty;
import com.cloudcc.mobile.view.fragment.MenuRightFragment;
import com.cloudcc.mobile.view.mymodel.ParseJson;
import com.cloudcc.mobile.view.mymodel.my;
import com.cloudcc.mobile.view.mymodel.mydaishenpi;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.adapter.FragmentAdapter;
import com.mypage.view.fragment.DetailFragment;
import com.mypage.view.fragment.DigestFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 摘要及其详情页
 * 
 * @author zys
 * 
 */
public class ApprovalPendingActivity extends FragmentActivity implements
		OnClickListener,IEventLife {
    public static ApprovalPendingActivity instance = null;
	private SlidingMenu menu_R;
	private Button mSelectorPerson;
	private ImageView mBack;
	private TextView title;
	private List<View> mPoint;
	private TextView textViewApproval;
	private TextView textViewDetail;
	private ImageView id_tab_line_iv;
	private ViewPager pprovalViewpager;
	private List<Fragment> mFragmentList = new ArrayList<Fragment>();
	private FragmentAdapter mFragmentAdapter;
	private DigestFragment mDigestFragment;
	private DetailFragment mDetailFragment;
	// ViewPager的当前选中页
	private int currentIndex;
	// 记录上一次点的位置
	private int oldPosition = 0;
	// 屏幕的宽度
	private int screenWidth;
	LinearLayout.LayoutParams lp;
	private ListView mTimeLine;
	private TextView approvalname,ownertime;

	private LinearLayout btnRatify;// 批准
	private LinearLayout btnRefuse;// 拒绝
	private LinearLayout btnAllocation;// 重新分配
	private ImageView btnRatifyimage,btnRefuseiamge,btnAllocationimage;

	/**
	 * 准备放置其他页面的控件
	 */
	private my model = null;
	private String objecttype;
	private String relatedId;
	private String actorId;
    private String ownername;
    private String ownerid;
	private TextView message_num_tz;
	private TextView message_num_99;
	private RelativeLayout relingdang;
	private String recordId;
//	@Bind(R.id.message_num_tz)
//	TextView message_num_tz;
//	@Bind(R.id.message_num_99)
//	TextView message_num_99;
//	@Bind(R.id.relingdang)
//	RelativeLayout relingdang;
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
	 */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.approval_pending_activity);
        instance = this;
		callLogLoadingDialog  = new CallLogLoadingDialog(this);
		initBoardCase();
		initView();
		initScreen();
//		if("tongzhishenpi".equals(getIntent().getStringExtra("tongzhi"))){
//			recordId = getIntent().getStringExtra("Recore_Id");
//			initTongzhi(recordId);
//		}else{
			initData();
//		}
		initListener();
		initMenu();
		register();
	}


	public void initBoardCase() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("finish");
		registerReceiver(broadcastReceiver, filter);
	}

	public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			unregisterReceiver(this);
			ApprovalPendingActivity.this.finish();
		}
	};
	@Override
	protected void onResume() {
		super.onResume();
		btnRatifyimage.setImageDrawable(getResources().getDrawable(R.drawable.appro_pizhun_default));
		btnRefuseiamge.setImageDrawable(getResources().getDrawable(R.drawable.appro_jujue_default));
		btnAllocationimage.setImageDrawable(getResources().getDrawable(R.drawable.appro_chongxin_default));
	}
	public void initView() {
		// TODO Auto-generated method stub
		pprovalViewpager = (ViewPager) findViewById(R.id.pprovalViewpager);
		textViewApproval = (TextView) findViewById(R.id.textViewApproval);
		textViewDetail = (TextView) findViewById(R.id.textViewDetail);
		id_tab_line_iv = (ImageView) findViewById(R.id.id_tab_line_iv);
		btnRatify = (LinearLayout) findViewById(R.id.btnRatify);
		btnRefuse = (LinearLayout) findViewById(R.id.btnRefuse);
		btnAllocation = (LinearLayout) findViewById(R.id.btnAllocation);
		btnRatifyimage = (ImageView) findViewById(R.id.pz_iv);
		btnRefuseiamge= (ImageView) findViewById(R.id.jujue_iv);
		btnAllocationimage= (ImageView) findViewById(R.id.cx_iv);
		message_num_tz = (TextView)findViewById(R.id.message_num_tz);
		message_num_99 = (TextView)findViewById(R.id.message_num_99);
		relingdang = (RelativeLayout)findViewById(R.id.relingdang);
//		textViewApproval.setTextColor(Color.BLUE);
		lp = (LinearLayout.LayoutParams) id_tab_line_iv.getLayoutParams();
		title = (TextView) findViewById(R.id.bar_title_text);
		mBack = (ImageView) findViewById(R.id.bar_back);
		mPoint = new ArrayList<View>();
		mPoint.add(findViewById(R.id.pointView1));
		mPoint.add(findViewById(R.id.pointView2));
		mTimeLine = (ListView) findViewById(R.id.vertical_timeline);
//		approvalname,owner,approvaltime
		approvalname =  (TextView) findViewById(R.id.textViewshenpiname);
		ownertime =  (TextView) findViewById(R.id.shenpi_own_time);
	}
String isbeizhu = "true";
	public void initData() {
		if (model == null) {
			model = (my) getIntent().getSerializableExtra("extra");
//			com.litesuits.android.log.Log.d("chuandishuju", "shuju"
//					+ model.actdate);
		}
		String zhaiyao = getIntent().getStringExtra("zhaiyao");
        //requestbeizhu(model.workItemid);
		title.setText("待审批");
		Log.d("----","22222");
		mDigestFragment = new DigestFragment();
		mDetailFragment = new DetailFragment();
		mFragmentList.add(mDigestFragment);
		mFragmentList.add(mDetailFragment);
		mFragmentAdapter = new FragmentAdapter(
				this.getSupportFragmentManager(), mFragmentList);
		pprovalViewpager.setAdapter(mFragmentAdapter);
		pprovalViewpager.setCurrentItem(0);
		mPoint.get(0).setBackgroundResource(
				R.drawable.approval_paager_origin_add);
		objecttype = model.objtype;
		relatedId = model.objid;
		actorId = model.actorid;
        ownername = model.ownername;
        ownerid = model.ownerid;
		approvalname.setText(model.objname);
		try {
			ownertime.setText(model.ownername+" · "+model.actdate.substring(0,10));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Bundle bundle = new Bundle();
		bundle.putString("objecttype", objecttype);
		bundle.putString("relatedId", relatedId);
		bundle.putString("actorid", actorId);
        bundle.putString("ownername", ownername);
        bundle.putString("ownerid", ownerid);
		// bundle.putString("approvalType", model.a);// 数据获取再动态该审批类型
		bundle.putString("personName", model.actor);
		bundle.putString("sendTime", model.actdate);
		bundle.putString("name", model.objname);
		if (!"".equals(zhaiyao) && null != zhaiyao) {
			zhaiyao = zhaiyao.trim();
			bundle.putString("gigest", zhaiyao.replace("&nbsp;", "\n"));
		} else {
			bundle.putString("gigest",
					"无摘要");
		}
		mDigestFragment.setArguments(bundle);
		mDetailFragment.setArguments(bundle);

		pprovalViewpager.setOnPageChangeListener(new OnPageChangeListener() {
			/**
			 * state滑动中的状态 有三种状态（0，1，2） 1：正在滑动 2：滑动完毕 0：什么都没做。
			 */
			@Override
			public void onPageScrollStateChanged(int state) {

			}

			/**
			 * position :当前页面，及你点击滑动的页面 offset:当前页面偏移的百分比
			 * offsetPixels:当前页面偏移的像素位置
			 */
			@Override
			public void onPageScrolled(int position, float offset,
					int offsetPixels) {

				Log.e("offset:", offset + "");
				/**
				 * 利用currentIndex(当前所在页面)和position(下一个页面)以及offset来
				 * 设置mTabLineIv的左边距 滑动场景： 记3个页面, 从左到右分别为0,1,2 0->1; 1->2; 2->1;
				 * 1->0
				 */

				if (currentIndex == 0 && position == 0)// 0->1
				{
					lp.leftMargin = (int) (offset * (screenWidth * 1.0 / 2) + currentIndex
							* (screenWidth / 2));

				} else if (currentIndex == 1 && position == 0) // 1->0
				{
					lp.leftMargin = (int) (-(1 - offset)
							* (screenWidth * 1.0 / 2) + currentIndex
							* (screenWidth / 2));

				}
				id_tab_line_iv.setLayoutParams(lp);
			}

			@Override
			public void onPageSelected(int position) {
				resetTextView();
				switch (position) {
				case 0:
//					textViewApproval.setTextColor(Color.BLUE);

					break;
				case 1:
//					textViewDetail.setTextColor(Color.BLUE);

					break;

				}
				mPoint.get(oldPosition).setBackgroundResource(
						R.drawable.approval_paager_origin);
				mPoint.get(position).setBackgroundResource(
						R.drawable.approval_paager_origin_add);
				currentIndex = position;
				oldPosition = position;
				Log.e("=======================", String.valueOf(position));
			}
		});

	}

	public void initListener() {
//		message_right.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//
//			}
//		});
		textViewApproval.setOnClickListener(this);
		textViewDetail.setOnClickListener(this);
		mBack.setOnClickListener(this);
		btnRatify.setOnClickListener(this);
		btnRefuse.setOnClickListener(this);
		btnAllocation.setOnClickListener(this);
		relingdang.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.textViewApproval:
			pprovalViewpager.setCurrentItem(0);
			break;

		case R.id.textViewDetail:
			pprovalViewpager.setCurrentItem(1);
			break;
		case R.id.bar_back:
			finish();
			break;
		case R.id.btnRatify:// 批准
			btnRatifyimage.setImageDrawable(getResources().getDrawable(R.drawable.appro_pizhun_press));
			if("true".equals(isbeizhu)){
			Intent intent = new Intent(ApprovalPendingActivity.this,
					ApproveActivityDialog.class);intent.putExtra("weizhi","xiangqing");
			intent.putExtra("workItemId", model.workItemid);//
			intent.putExtra("isRequired",isbeizhu);
			// 正式获取的时候把双引号去掉，现在只是加载的是静止的数据
			startActivity(intent);
			}else{
//				zidong("Approved");
				setDataNetWork("doApproved");
			}
			break;
		case R.id.btnRefuse:// 拒绝
			btnRefuseiamge.setImageDrawable(getResources().getDrawable(R.drawable.appro_jujue_press));
			if("true".equals(isbeizhu)) {
				Intent intentb = new Intent(ApprovalPendingActivity.this,
						RefuseActivityDialog.class);
				intentb.putExtra("weizhi","xiangqing");
				intentb.putExtra("isRequired", isbeizhu);
				intentb.putExtra("workItemId", model.workItemid);//
				// 正式获取的时候把双引号去掉，现在只是加载的是静止的数据
				startActivity(intentb);
			}else {
//				zidong("Rejected");
				setDataNetWork("doRejected");
			}
			break;
		case R.id.btnAllocation:// 重新分配
			btnAllocationimage.setImageDrawable(getResources().getDrawable(R.drawable.appro_chongxin_press));
			Intent intents = new Intent(ApprovalPendingActivity.this,
					MyApproval.class);
			intents.putExtra("weizhi","xiangqing");
            intents.putExtra("isRequired",isbeizhu);
			intents.putExtra("workItemId", model.workItemid);//
			intents.putExtra("personname", model.actor);//
			// 正式获取的时候把双引号去掉，现在只是加载的是静止的数据
			startActivity(intents);

			break;
			case R.id.relingdang:
				menu_R.showMenu();
				break;
		}
	}

	/**
	 * 重置颜色
	 */
	private void resetTextView() {
		textViewApproval.setTextColor(Color.BLACK);
		textViewDetail.setTextColor(Color.BLACK);
	}

	public void initScreen() {
		/**
		 * 设置滑动条的宽度为屏幕的1/3(根据Tab的个数而定)
		 */

		DisplayMetrics dpMetrics = new DisplayMetrics();
		getWindow().getWindowManager().getDefaultDisplay()
				.getMetrics(dpMetrics);
		screenWidth = dpMetrics.widthPixels;
		LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) id_tab_line_iv
				.getLayoutParams();
		lp.width = screenWidth / 2;
		id_tab_line_iv.setLayoutParams(lp);

	}
    public void requestbeizhu(String ids){
        // 拒绝
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "isRequired");
        params.addBodyParameter("ids", ids);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        // TODO Auto-generated method stub
                        String result = arg0.result;
                        Gson gson = new Gson();
                        mydaishenpi ss = gson.fromJson(arg0.result,
                                mydaishenpi.class);
                        isbeizhu = ss.data.isRequired;
                    }
                });

    }

	public void onEventMainThread(MessageNumX event) {

		message_num_tz.setText(event.messageNumX+"");
		if(event.messageNumX>0) {
			message_num_tz.setVisibility(View.VISIBLE);
			if(event.messageNumX>99) {
				message_num_tz.setVisibility(View.INVISIBLE);
				message_num_99.setVisibility(View.VISIBLE);
			}

		}else {
			message_num_tz.setVisibility(View.INVISIBLE);
			message_num_99.setVisibility(View.INVISIBLE);
		}

	}
	private void MessageSetNCL(){
		long messagenum = 0;
		messagenum= RunTimeManager.getInstance().getMessageNx();
		message_num_tz.setText(messagenum+"");

		if(messagenum>0) {
			message_num_tz.setVisibility(View.VISIBLE);
			if(messagenum>99) {
				message_num_tz.setVisibility(View.INVISIBLE);
				message_num_99.setVisibility(View.VISIBLE);
			}

		}else {
			message_num_tz.setVisibility(View.INVISIBLE);
			message_num_99.setVisibility(View.INVISIBLE);
		}

	}

	private void initMenu() {
		Fragment leftMenuFragment = new MenuRightFragment();
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.id_Right_menu_frame, leftMenuFragment).commit();
		menu_R = new SlidingMenu(this);
		menu_R.setMode(SlidingMenu.RIGHT);
		menu_R.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); // 触摸边界拖出菜单
		menu_R.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu_R.setOffsetFadeDegree(0.4f);
		menu_R.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		View viewRi = LayoutInflater.from(this).inflate(R.layout.right_menu_id,
				null);
		menu_R.setMenu(viewRi);
	}

	CallLogLoadingDialog callLogLoadingDialog ;
	public void zidong(String zhuangtai){
		pizhun(zhuangtai);
		callLogLoadingDialog.show();
		callLogLoadingDialog.settext("处理中...");
	}
	public void pizhun(String zhuangtai) {
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();

		params.addBodyParameter("userId",
				UserManager.getManager().getUser().userId);
		params.addBodyParameter("binding", RunTimeManager.getInstance()
				.getServerBinding());

		params.addBodyParameter("serviceName", "ajaxProcessMassThread");

		params.addBodyParameter("workItemId", model.workItemid);
		params.addBodyParameter("actionType",zhuangtai);
		params.addBodyParameter("comments", "");
		params.addBodyParameter("fprId", "");
		Log.d("hahahha", UrlManager.getInterfaceUrl() + params);
		utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						callLogLoadingDialog.dismiss();
						Intent intent = new Intent(ApprovalPendingActivity.this, TaskManagementActivty.class);
						intent.putExtra("chongxin","chongxinshibai");
						startActivity(intent);
					}
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						String result = arg0.result;
						callLogLoadingDialog.dismiss();
						Intent intent = new Intent(ApprovalPendingActivity.this, TaskManagementActivty.class);
						TaskManagementActivty.instance.finish();
						ApprovalPendingActivity.instance.finish();
						intent.putExtra("taskfinish","taskfinish");
						startActivity(intent);
					}
				});

	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegister();
	}
	private ApprovalEngineImpl engine = new ApprovalEngineImpl();
	public void initTongzhi(String recordId){
		engine.GetManagementTask_z(RunTimeManager.getInstance().getUserId(),1,recordId, new ResultCallBack<JsonObject>() {
			@Override
			public void onSuccess(JsonObject t) {
				JsonObject zhaoyao = (JsonObject) t.get("zymap");
				// JsonElement jsonElement2 = t.get("zymap");
				Log.d("getfield", "解析下一步");
				Gson gson = new Gson();
				ParseJson json = gson.fromJson(t, ParseJson.class);
				// com.litesuits.android.log.Log.d("taskmodel",
				// json.resultList.get(0).fr);
				List<ParseJson.Zu> list = new ArrayList<ParseJson.Zu>();
				list = json.resultList;
				model = list.get(0).data.get(0);
				initData();
			}
			@Override
			public void onFailure(ErrorInfo error) {
//				sign = true;
//				mptrframe.refreshComplete();
				Toast.makeText(ApprovalPendingActivity.this, R.string.qingqiushibai,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

//详情页面不走备注
public void setDataNetWork(String name) {
	HttpUtils utils = new HttpUtils();
	RequestParams params = new RequestParams();
	params.addBodyParameter("binding", RunTimeManager.getInstance()
			.getServerBinding());
	params.addBodyParameter("serviceName",name);
	params.addBodyParameter("data", createJson());

	utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
			new RequestCallBack<String>() {

				@Override
				public void onFailure(HttpException arg0, String arg1) {

					// TODO Auto-generated method stub
					Intent intent = new Intent(ApprovalPendingActivity.this,
							TaskManagementActivty.class);
//						if(workItemId.length()>30) {
//							intent.putExtra("chongxin", "chongxinmore");
//						}else{
					intent.putExtra("chongxinshibai","chongxin");
//						}
					startActivity(intent);
					sendBroadcast(new Intent().setAction("finish"));
					finish();
				}

				@Override
				public void onSuccess(ResponseInfo<String> arg0) {
					// TODO Auto-generated method stub
					sendBroadcast(new Intent().setAction("taskfinish"));
					Intent intent = new Intent(ApprovalPendingActivity.this,
							TaskManagementActivty.class);
					TaskManagementActivty.instance.finish();
					try {
						ApprovalPendingActivity.instance.finish();
					} catch (Exception e) {
						e.printStackTrace();
					}
					intent.putExtra("taskfinish","xiangqingpizhun");
					startActivity(intent);

					sendBroadcast(new Intent().setAction("finish"));
					finish();

				}
			});
}
	public String createJson() {
		JSONObject object = new JSONObject();
		try {
//			params.addBodyParameter("workItemId", workItemId);
//			params.addBodyParameter("comments", content);
			object.put("workItemId", model.workItemid);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object.toString();

	}

}
